//
//  KeyboardMoveView.m
//  Prizes
//
//  Created by Leafc on 13年5月7日.
//  Copyright (c) 2013年 Leafc. All rights reserved.
//

#import "KeyboardMoveView.h"

#define kKeyboardHeight 216.0f

@interface KeyboardMoveView ()

- (void)moveView:(UITextField *)textField leaveView:(BOOL)leave;

@end


@implementation KeyboardMoveView

- (id)initWithRootView:(UIView *)view {
    self = [super init];
    if (self) {
        rootView = view;
    }
    return self;
}

- (void)registeredTextField:(UITextField *)textField
{
    textField.delegate = self;
    [textField addTarget:self action:@selector(textFieldEditingDidEndOnExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField   
{   
    [self moveView:textField leaveView:NO];   
}   

- (void)textFieldDidEndEditing:(UITextField *)textField;   
{   
    [self moveView:textField leaveView:YES];
    [textField resignFirstResponder];
}

- (void)textFieldEditingDidEndOnExit:(UITextField *)textField
{
    [textField resignFirstResponder];
}

#pragma mark - TextField Keyboard 

- (void)moveView:(UITextField *)textField leaveView:(BOOL)leave   
{   
    CGFloat screenHeight = rootView.frame.size.height;
    CGFloat keyboardHeight = kKeyboardHeight;
    CGFloat margin;
    
    CGRect fieldFrame = [rootView convertRect:textField.frame fromView:textField.superview];
    CGFloat textFieldOriginY = fieldFrame.origin.y;
    CGFloat textFieldHeight = fieldFrame.size.height;
    CGFloat textFieldFromButtomHeigth = screenHeight - textFieldOriginY - textFieldHeight; 
    
    if(!leave) { 
        if(textFieldFromButtomHeigth < keyboardHeight) {
            margin = keyboardHeight - textFieldFromButtomHeigth;
            keyBoardMargin = margin;
        } else { 
            margin= 0; 
            keyBoardMargin = 0; 
        } 
    }
    int movement = (leave ? keyBoardMargin : -margin);
    
    [UIView beginAnimations:nil context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES]; 
    rootView.frame = CGRectOffset(rootView.frame, 0, movement); 
    [UIView commitAnimations];
}  

@end
